import 'package:flutter/material.dart';
import 'package:yuan_hang_app/res/w_colors.dart';
import 'package:yuan_hang_app/res/w_dimens.dart';
import 'package:yuan_hang_app/utils/common_utils.dart';
import 'package:yuan_hang_app/utils/size_utils.dart';
import 'package:yuan_hang_app/utils/string_utils.dart';
import 'package:yuan_hang_app/widget/w_text.dart';
import 'package:yuan_hang_app/widget/w_toast.dart';
import '../../../../http/api.dart';
import '../../../../http/http_utils.dart';
import '../../../../utils/router_helper.dart';
import '../../../../widget/custom_search.dart';
import '../../../../widget/w_list_view.dart';

class DriveVechilePage extends StatefulWidget {
  const DriveVechilePage({super.key});

  @override
  State<DriveVechilePage> createState() => _DriveVechilePageState();
}

class _DriveVechilePageState extends State<DriveVechilePage> {
  List bookList = [];
  List currentDriveList = [];

  // 添加一个状态变量来跟踪当前选中的项的ID
  String selectedId = '';

  //定义一个状态，显示当前状态
  String status="";

  var mCurrentStatus;

  Map<String, dynamic> queryParams = {
    "pageNum": 1,
    "limit": 20,
  };

  String licenceNo = "";
  String id = "";

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        Container(
          height: 48.px,
          alignment: Alignment.center,
          child: WText(
            "试驾车辆",
            style: TextStyle(
                fontWeight: FontWeight.bold,
                color: WColors.mainTextColor,
                fontSize: WDimens.tsXLarge),
          ),
        ),
        // 文字标签按钮
        CustomSearch(
          hintText: "请输入车牌/车型",
          showSort: false,
          onTextChange: (text) {
            queryParams["queryParam"] = text;
            queryParams["pageNum"] = 1;
            CommonUtils.antiShake(filterDataList);
          },
        ),
        Expanded(
          child: WListView(
            padding: EdgeInsets.zero,
            itemBuilder: _noticeMsgItem,
            getDataList: (currentState, page) {
              mCurrentStatus = currentState;
              queryParams["pageNum"] = page;
              fetchDataList();
            },
          ),
        ),

        Padding(
          padding: EdgeInsets.symmetric(vertical: 10.px, horizontal: 15.px),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.end,
            children: [
              GestureDetector(
                onTap: () {
                  licenceNo = "";
                  id = "";
                  RouteHelper.maybePop(context, null);
                },
                child: Container(
                  height: 45.px,
                  width: 120.px,
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(24.px),
                      border:
                          Border.all(color: WColors.border, width: 1.px),
                      color: WColors.white),
                  child: WText(
                    "取消",
                    style: TextStyle(
                        color: WColors.mainTextColor,
                        fontSize: WDimens.tsMedium),
                  ),
                ),
              ),
              Expanded(
                child: GestureDetector(
                  onTap: () {
                    Map<String, Object> dataMap = {};
                    dataMap["licenceNo"] = licenceNo;
                    dataMap["id"] = id;
                    RouteHelper.maybePop(context, dataMap);
                  },
                  child: Container(
                    margin: EdgeInsets.only(left: 10.px),
                    height: 45.px,
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(24.px),
                        color: WColors.primaryColor),
                    child: WText(
                      "确定",
                      style: TextStyle(color: WColors.white, fontSize: 14.px),
                    ),
                  ),
                ),
              )
            ],
          ),
        )
      ],
    );
  }

  void fetchDataList() {
    mCurrentStatus.onRefreshData(bookList, queryParams["pageNum"]);
    HttpUtils().get(Api.getDriveVechileList).then((value) {
      Toast.dismissLoading();
      if (value.resultCode == 200) {
        List list = value.data ?? [];
        mCurrentStatus.onRefreshData(list, queryParams["pageNum"]);
        if (queryParams["pageNum"] == 1) {
          bookList.clear();
        }
        bookList.addAll(list);
      } else {
        mCurrentStatus?.onFail(value.errMsg);
      }
    }).catchError((e) {
      Toast.dismissLoading();
    });
  }

  void filterDataList() {
    //可以考虑将下面的数据在第一次请求时设置为不可变的集合替代每次请求获取bookList
    HttpUtils().get(Api.getDriveVechileList).then((value) {
      Toast.dismissLoading();
      if (value.resultCode == 200) {
        List list = value.data ?? [];
        bookList.clear();
        bookList.addAll(list);
      } else {
        mCurrentStatus?.onFail(value.errMsg);
      }
    }).catchError((e) {
      Toast.dismissLoading();
    });

    ///开始重新设置集合
    mCurrentStatus.onRefreshData(bookList, queryParams["pageNum"]);
    List list = bookList.where((book) {
      return book['licenseNo'].contains(queryParams["queryParam"]) ||
          book['modelName'].contains(queryParams["queryParam"]);
    }).toList();
    mCurrentStatus.onRefreshData(list, queryParams["pageNum"]);
    if (queryParams["pageNum"] == 1) {
      bookList.clear();
    }
    bookList.addAll(list);
  }

  Widget _noticeMsgItem(context, index, currentDriveList) {
    Map item = currentDriveList[index];
    return GestureDetector(
        onTap: () {
          status=StringUtils.safeGetValue(item["status"]);
          if(status=="24591003"){
            Toast.toast("该车辆正在被${item['createdBy']}顾问使用");
            return;
          }else{
            selectedId = item["id"];
            licenceNo = StringUtils.safeGetValue(item["licenseNo"]);
            id = StringUtils.safeGetValue(item["id"]);
            setState(() {
              // 更新状态以触发重新绘制
            });
          }
        },
        child: Container(
            padding: EdgeInsets.symmetric(horizontal: 15.px, vertical: 5.px),
            decoration: BoxDecoration(
                border: Border(
                    bottom: BorderSide(width: 0.8.px, color: WColors.border)),
                color: WColors.white
                // 根据selectedId决定是否添加蓝色背景
                // color: selectedId == item["id"] ? WColors.primaryColor : Colors.white,
                ),
            child: Row(
              children: [
                Expanded(
                    child: Column(
                        mainAxisAlignment: MainAxisAlignment.start,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                      WText(
                        StringUtils.safeGetValue(item["licenseNo"]),
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                          fontSize: WDimens.tsLarge,
                          color: WColors.mainTextColor,
                        ),
                      ),
                      SizedBox(
                        height: 5.px,
                      ),
                      WText(
                        StringUtils.safeGetValue(item["modelName"]),
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                          fontSize: WDimens.tsLarge,
                          color: WColors.mainTextColor,
                        ),
                      ),
                    ])),
                Offstage(
                  offstage: selectedId != item["id"],
                  child: Image.asset(
                    "images/ic_right_check.png",
                    width: 24.px,
                  ),
                )
              ],
            )));
  }

  @override
  void initState() {
    super.initState();
    // fetchDataList();
  }
}
